﻿namespace PowerSong.UserInterface
    {
    using System.Windows.Controls;
    using System.Collections.Generic;

    /// <summary>
    /// Interaction logic for CheckListBox.xaml.
    /// </summary>
    public partial class CheckListBox : ListBox
        {

        public CheckListBox()
            {
            InitializeComponent();
            }

        public delegate void CheckedChangedDelegate(object item, bool isChecked);

        public event CheckedChangedDelegate CheckedChanged = null;

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
            {
            this.SelectedItem = null;
            }

        public object[] GetCheckedItems()
            {
            var result = new List<object>();
            foreach (CheckListBoxItem item in this.Items)
                {
                if (item.IsChecked == true) result.Add(item.Value);
                }
            return result.ToArray();
            }

        internal void CheckAllItems()
            {
            foreach (CheckListBoxItem item in this.Items)
                {
                item.IsChecked = true;
                }
            }

        internal void UncheckAllItems()
            {
            foreach (CheckListBoxItem item in this.Items)
                {
                item.IsChecked = false;
                }
            }

        internal void SetCheckedItems(IEnumerable<object> itemsToCheck, bool uncheckAllOtherItems = false)
            {

            // Uncheck all items first if necessary
            if (uncheckAllOtherItems == true)
                {
                foreach (CheckListBoxItem item in this.Items)
                    {
                    item.IsChecked = false;
                    }
                }

            // Check the given items
            foreach (var itemToCheck in itemsToCheck)
                {
                foreach (CheckListBoxItem itemInList in this.Items)
                    {
                    if (itemInList.Value == itemToCheck)
                        {
                        itemInList.IsChecked = true;
                        }
                    }
                }

            }

        private void CheckBox_Checked(object sender, System.Windows.RoutedEventArgs e)
            {
            var item = (CheckListBoxItem)((CheckBox)sender).DataContext;
            if (CheckedChanged != null) CheckedChanged(item.Value, item.IsChecked);
            }

        private void CheckBox_Unchecked(object sender, System.Windows.RoutedEventArgs e)
            {
            var item = (CheckListBoxItem)((CheckBox)sender).DataContext;
            if (CheckedChanged != null) CheckedChanged(item.Value, item.IsChecked);
            }

        }

    }
